﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Qianke.Core.Common.Http
{
    /// <summary>
    /// Http连接操作帮助类
    /// </summary>
    public class HttpHelper
    {

        static HttpHelper()
        {
            ServicePointManager.DefaultConnectionLimit = 200;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
        }

        public static async Task<HttpResult> GetHtmlEx(HttpConfig config)
        {
            var task = Task.Run(() => GetHtml(config));
            await Task.Delay(0);
            if (task.Wait(config.Timeout))
                return task.Result;
            return new HttpResult()
            {
                StatusCode = System.Net.HttpStatusCode.RequestTimeout,
                StatusDescription = "请求超时：" + config.URL,
            };
        }

        #region 预定义方法或者变更
        public static Task<HttpResult> GetHtml(HttpConfig config)
        {
            return GetHtml(config, null);
        }

        /// <summary>
        /// 根据相传入的数据，得到相应页面数据
        /// </summary>
        /// <param name="item">参数类对象</param>
        /// <returns>返回HttpResult类型</returns>
        public static async Task<HttpResult> GetHtml(HttpConfig config,Action<HttpWebRequest> fnOption)
        {
            //返回参数
            HttpResult result = new HttpResult();
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                //准备参数
      
                request = await SetRequest(config, fnOption);

            }
            catch (Exception ex)
            {
                result = new HttpResult();
                result.Cookie = string.Empty;
                result.Header = null;
                result.Html = ex.Message;
                result.StatusDescription = "配置参数时出错：" + ex.Message;
                return result;
            }
            try
            {
                
                #region 得到请求的response
                using (response = (HttpWebResponse) await request.GetResponseAsync())
                {
                    result.StatusCode = response.StatusCode;
                    result.StatusDescription = response.StatusDescription;
                    result.Header = response.Headers;
                    if (response.Cookies != null) result.CookieCollection = response.Cookies;
                    if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
                    MemoryStream _stream = new MemoryStream();
                    //GZIIP处理
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //开始读取流并设置编码方式
                        //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = await GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));

                    }
                    else
                    {
                        //开始读取流并设置编码方式
                        //response.GetResponseStream().CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = await GetMemoryStream(response.GetResponseStream());
                    }
                    //获取Byte
                    byte[] ResponseByte = _stream.ToArray();
                    _stream.Close();
                    if (ResponseByte != null & ResponseByte.Length > 0)
                    {
                        //是否返回Byte类型数据
                        if (config.ResultType == DataType.缓冲区) result.ResultByte = ResponseByte;
                        //从这里开始我们要无视编码了
                        if (config.Encoding == null)
                        {
                            var meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                            string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToLower().Trim() : string.Empty;
                            if (c.Length > 2)
                            {
                                try
                                {
                                    if (c.IndexOf(" ") > 0) c = c.Substring(0, c.IndexOf(" "));
                                    config.Encoding = Encoding.GetEncoding(c.Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
                                }
                                catch
                                {
                                    if (string.IsNullOrEmpty(response.CharacterSet))
                                        config.Encoding = Encoding.UTF8;
                                    else
                                        config.Encoding = Encoding.GetEncoding(response.CharacterSet);
                                }
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(response.CharacterSet))
                                    config.Encoding = Encoding.UTF8;
                                else
                                    config.Encoding = Encoding.GetEncoding(response.CharacterSet);
                            }
                        }
                        //得到返回的HTML
                        result.Html = config.Encoding.GetString(ResponseByte);
                    }
                    else
                    {
                        //得到返回的HTML
                        result.Html = "本次请求并未返回任何数据";
                    }
                }
                #endregion
            }
            catch (WebException ex)
            {
                //这里是在发生异常时返回的错误信息
                response = (HttpWebResponse)ex.Response;
                result.Html = ex.Message;
                //返回的状态码非200   但是也有存在可能在 返回的流里面有数据的
                try
                {
                    var buffer = await GetMemoryStream(response.GetResponseStream());
                    result.Html = Encoding.UTF8.GetString(buffer.ToArray());
                }
                catch
                {

                }
                if (response != null)
                {
                    result.StatusCode = response.StatusCode;
                    result.StatusDescription = response.StatusDescription;
                }
            }
            catch (Exception ex)
            {
                result.Html = ex.Message;
            }
            if (config.IsToLower)
                result.Html = result.Html.ToLower();
            return result;
        }

        /// <summary>
        /// 调用接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static async Task<ReturnInfo> CallApi(string url, string param, Encoding encoding)
        {
            var config = new HttpConfig()
            {
                URL = url,
                Encoding = encoding,
                Method = "POST",
                Postdata = param,
                ResultType = DataType.字符串,
                PostEncoding = encoding,
                PostDataType = DataType.字符串,
                KeepAlive = true,
                ContentType= "application/json",
            };
            var result = await GetHtmlEx(config);
            if (result.StatusCode ==  HttpStatusCode.OK)
                return new ReturnInfoData(result.Html);
            return new ReturnInfo(result.StatusCode.ToString(),result.Html);
        }

        /// <summary>
        /// 4.0以下.net版本取数据使用
        /// </summary>
        /// <param name="streamResponse">流</param>
        private static async Task<MemoryStream> GetMemoryStream(Stream streamResponse)
        {
            MemoryStream _stream = new MemoryStream();
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = await streamResponse.ReadAsync(buffer, 0, Length);
            while (bytesRead > 0)
            {
                _stream.Write(buffer, 0, bytesRead);
                bytesRead = await streamResponse.ReadAsync(buffer, 0, Length);
            }
            return _stream;
        }
        /// <summary>
        /// 为请求准备参数
        /// </summary>
        ///<param name="item">参数列表</param>
        private static async Task<HttpWebRequest> SetRequest(HttpConfig item, Action<HttpWebRequest> fnOption)
        {
            HttpWebRequest request = null;
            // 验证证书
            if (!string.IsNullOrEmpty(item.CerPath))
            {
                //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //初始化对像，并设置请求的URL地址
                request = (HttpWebRequest)WebRequest.Create(item.URL);
                SetCerList(item, request);
                //将证书添加到请求里
                request.ClientCertificates.Add(new X509Certificate(item.CerPath));
            }
            else
            {
                //初始化对像，并设置请求的URL地址
                request = (HttpWebRequest)WebRequest.Create(item.URL);
                SetCerList(item, request);
            }

            //设置Header参数
            if (item.Header != null && item.Header.Count > 0)
                foreach (string key in item.Header.AllKeys)
                {
                    request.Headers.Add(key, item.Header[key]);
                }
            // 设置代理
            SetProxy(item, request);
            if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
            request.ServicePoint.Expect100Continue = item.Expect100Continue;
            //请求方式Get或者Post
            request.Method = item.Method;
            request.Timeout = item.Timeout;
            request.KeepAlive = item.KeepAlive;
            request.ReadWriteTimeout = item.ReadWriteTimeout;
            //Accept
            request.Accept = item.Accept;
            //ContentType返回类型
            request.ContentType = item.ContentType;
            //UserAgent客户端的访问类型，包括浏览器版本和操作系统信息
            request.UserAgent = item.UserAgent;

            //设置安全凭证
            request.Credentials = item.ICredentials;
            //设置Cookie
            SetCookie(item, request);
            //来源地址
            request.Referer = item.Referer;
            //是否执行跳转功能
            request.AllowAutoRedirect = item.Allowautoredirect;
            var uri = new Uri(item.URL);
            //设置Host
            request.Host = uri.Host;

            fnOption?.Invoke(request);
            //设置Post数据
            await SetPostData(item, request);
            //设置最大连接
            if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
            return request;
        }

        /// <summary>
        /// 设置多个证书
        /// </summary>
        /// <param name="item"></param>
        private static void SetCerList(HttpConfig item, HttpWebRequest request)
        {
            if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
            {
                foreach (var c in item.ClentCertificates)
                {
                    request.ClientCertificates.Add(c);
                }
            }
        }
        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="item">Http参数</param>
        private static void SetCookie(HttpConfig item, HttpWebRequest request)
        {
            if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
        }
        /// <summary>
        /// 设置Post数据
        /// </summary>
        /// <param name="item">Http参数</param>
        private static async Task SetPostData(HttpConfig item, HttpWebRequest request)
        {
            //验证在得到结果时是否有传入数据
            if (request.Method.Trim().ToLower().Contains("post"))
            {
                if (item.PostEncoding == null)
                    item.PostEncoding = Encoding.UTF8;
                byte[] buffer = null;
                //写入Byte类型
                if (item.PostDataType == DataType.缓冲区 && item.PostdataByte != null && item.PostdataByte.Length > 0)
                {
                    //验证在得到结果时是否有传入数据
                    buffer = item.PostdataByte;
                }//写入文件
                else if (item.PostDataType == DataType.文件 && !string.IsNullOrEmpty(item.Postdata))
                {
                    using (var r = new FileStream(item.Postdata,FileMode.OpenOrCreate, FileAccess.Read))
                    {
                        using(var ms = new MemoryStream())
                        {
                            var tBuffer = new byte[1024];
                            int nSize = 0;
                            while((nSize = await r.ReadAsync(tBuffer, 0, 1024)) > 0)
                                await ms.WriteAsync(buffer, 0, nSize);
                            buffer = ms.ToArray();
                        }
                    }
                } //写入字符串
                else if (!string.IsNullOrEmpty(item.Postdata))
                {
                    buffer = item.PostEncoding.GetBytes(item.Postdata);
                    if (item.IsZipSend)
                    {
                        request.Headers.Add("Content-Encoding", "gzip");
                        request.Headers.Add("Accept-Encoding", "gzip");
                        using (var outPut = new MemoryStream())
                        {
                            using (var zipStream = new GZipStream(outPut, CompressionMode.Compress))
                                await zipStream.WriteAsync(buffer, 0, buffer.Length);
                            buffer = outPut.ToArray();
                        }
                    }
                }
                if (buffer != null)
                {
                    request.ContentLength = buffer.Length;
                    await request.GetRequestStream().WriteAsync(buffer, 0, buffer.Length);
                }
            }
        }
        /// <summary>
        /// 设置代理
        /// </summary>
        /// <param name="item">参数对象</param>
        private static void SetProxy(HttpConfig item, HttpWebRequest request)
        {
            if (!string.IsNullOrEmpty(item.ProxyIp))
            {
                bool isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy");
                if (!isIeProxy)
                {
                    //设置代理服务器
                    if (item.ProxyIp.Contains(":"))
                    {
                        string[] plist = item.ProxyIp.Split(':');
                        WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
                        //建议连接
                        myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
                        //给当前请求对象
                        request.Proxy = myProxy;
                    }
                    else
                    {
                        WebProxy myProxy = new WebProxy(item.ProxyIp, false);
                        //建议连接
                        myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
                        //给当前请求对象
                        request.Proxy = myProxy;
                    }
                }
                else if (isIeProxy)
                {
                    //设置为IE代理
                }
                else
                {
                    request.Proxy = item.WebProxy;
                }
            }
            else
                request.Proxy = null;
        }
        /// <summary>
        /// 回调验证证书问题
        /// </summary>
        /// <param name="sender">流对象</param>
        /// <param name="certificate">证书</param>
        /// <param name="chain">X509Chain</param>
        /// <param name="errors">SslPolicyErrors</param>
        /// <returns>bool</returns>
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
        #endregion
    }
}
